<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    :isDetail="false"
    :width="getIsMobile ? '95%':'80%'"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #cron="{ model, field }">
        <div class="flex justify-center">
          <a-input placeholder="请输入"v-model:value="model[field]" />
          <a-button style="margin-left: 10px;" type="primary" @click=""> <a target="_blank" href="https://www.pppet.net/">在线生成Cron</a> </a-button>
      </div>
      </template>

      <template #listConfig="{ model, field }">
        <CodeEditor v-model:value="model[field]" :mode="MODE.JSON" />
      </template>
      <template #detailConfig="{ model, field }">
        <CodeEditor v-model:value="model[field]" :mode="MODE.JSON" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { useAppInject } from '@/hooks/web/useAppInject';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './grabtemplate.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { CodeEditor, MODE } from '@/components/CodeEditor';

  import { getMenuList } from '@/api/demo/system';

  const { getIsMobile } = useAppInject();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  // const treeData = ref<TreeItem[]>([]);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    // if (unref(treeData).length === 0) {
    //   treeData.value = (await getMenuList()) as any as TreeItem[];
    // }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增任务' : '编辑任务'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
